<?php


namespace backend\components\adapter;

use Yii;
use yii\helpers\FileHelper;
use backend\models\Clients;
use backend\components\InstallerAdapter;
use backend\modules\widgets\models\Widgets;

/**
 * description of WidgetAdapter
 *
 * @author FireLoong
 */
class WidgetAdapter extends InstallerAdapter
{

    protected $clientId;
    protected $clientName;

    /**
     * @inheritDoc
     */
    protected function setupInstallPaths()
    {
        $this->clientName = (string)$this->manifest->attributes()->client;
        $client = Clients::findOne(['name' => $this->clientName]);
        if (is_null($client)) {
            $params = [
                'action' => Yii::t('installer', strtoupper($this->route)),
                'error' => Yii::t('installer', 'ERROR_UNKNOWN_CLIENT', $this->clientName)
            ];
            throw new \RuntimeException(Yii::t('installer', 'ABORT_ROLLBACK', $params));
        }
        $this->clientId = $client->id;
        $basePath = Yii::getAlias('@root' . $client->path);
        if (empty($this->element)) {
            $msg = Yii::t('installer', 'ABORT_THEME_NO_FILE', Yii::t('installer', strtoupper($this->route)));
            throw new \RuntimeException($msg);
        }

        $this->parent->setPath('extension_root', $basePath . '/widgets/' . $this->element);
    }

    /**
     * @inheritDoc
     */
    protected function checkExistingExtension()
    {
        try {
            $this->currentExtensionId = $this->extension->findOne([
                'element' => $this->element,
                'type' => $this->type,
                'client_id' => $this->clientId
            ]);
        } catch (\yii\db\Exception $e) {
            $params = [
                'action' => Yii::t('installer', strtoupper($this->route)),
                'error' => $e->getMessage()
            ];
            throw new \RuntimeException(Yii::t('installer', 'ABORT_ROLLBACK', $params), $e->getCode(), $e);
        }
    }

    /**
     * @inheritDoc
     */
    protected function copyBaseFiles()
    {
        if ($this->parent->parseFiles($this->manifest->files) === false) {
            throw new \RuntimeException(Yii::t('installer', 'ABORT_THEME_INSTALL_FAIL_COPY_FILES'));
        }

        foreach ($this->manifest->files->children() as $child) {
            if ($child->attributes()->theme) {
                $theme = (string)$child->attributes()->theme;
                $childType = $child->getName() === 'folder' ? 'folder' : 'file';
                $startsWith = \yii\helpers\StringHelper::startsWith((string)$child, $theme . '/');
                $source = $this->parent->source . '/' . (string)$child;
                if ($startsWith) {
                    $inThemePath = '/widgets/' . $this->element . substr((string)$child, strlen($theme));
                } else {
                    $inThemePath = (string)$child;
                }
                $themePath = Yii::getAlias('@root') . '/' . $this->clientName . '/themes/' . $theme;
                $dest = $themePath . $inThemePath;
                if ($childType === 'folder') {
                    if (is_dir($source)) {
                        FileHelper::copyDirectory($source, $dest);
                    }
                } else {
                    if (is_file($source)) {
                        FileHelper::createDirectory(dirname($dest));
                        copy($source, $dest);
                    }
                }
            }
        }
    }

    /**
     * @inheritDoc
     */
    protected function parseOptionalTags()
    {
        $this->parent->parseMessages($this->manifest->messages, $this->clientName);
    }

    /**
     * @inheritDoc
     */
    protected function storeExtension()
    {
        if ($this->currentExtensionId) {
            $this->extension = $this->currentExtensionId;
        } else {
            $this->extension->type = 'widget';
            $this->extension->element = $this->element;
            $this->extension->folder = '';
            $this->extension->enabled = 1;
            $this->extension->protected = 0;
            $this->extension->client_id = $this->clientId;
            $this->extension->params = $this->parent->getParams();
            $this->extension->status = 1;
            $this->extension->ordering = 0;
        }
        $this->extension->name = $this->name;
        $this->extension->manifest_cache = $this->parent->generateManifestCache();

        if (!$this->extension->save()) {
            $params = [
                'action' => Yii::t('installer', strtoupper($this->route)),
                'error' => $this->parent->errorsToString($this->extension->getErrors())
            ];
            throw new \RuntimeException(Yii::t('installer', 'ABORT_ROLLBACK', $params));
        }

        $this->parent->pushStep([
            'type' => 'extension',
            'id' => $this->extension->id
        ]);

        if ($this->route === 'install') {
            $widgets = new Widgets();
            $widgets->title = $this->name;
            $widgets->content = '';
            $widgets->widget = $this->element;
            $widgets->showtitle = 1;
            $widgets->params = '';
            $widgets->client_id = $this->clientId;
            $widgets->language = '*';
            $widgets->save();
        }
    }
}
